package com.sie.config;

import com.hustcad.plm.pdm.common.service.remote.config.LicenseConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//自定义修改天喻系统启动是的bean 避开许可证生成逻辑
@Component
public class MyBeanConfig implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        beanDefinitionRegistry.removeBeanDefinition("licenseConfig");
        beanDefinitionRegistry.removeBeanDefinition("localLicenseBackup");

        BeanDefinition beanDefinition =  new RootBeanDefinition(MyLicenseConfig.class);
        BeanDefinition licenseBean =  new RootBeanDefinition(getLicenseBean().getClass());

        beanDefinitionRegistry.registerBeanDefinition("licenseConfig", beanDefinition);
        beanDefinitionRegistry.registerBeanDefinition("localLicenseBackup", licenseBean);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    }

    public LicenseConfig.LicenseBean getLicenseBean() {
        Class<?> aClass = null;
        try {
            aClass = Class.forName("com.hustcad.plm.pdm.common.service.remote.config.LicenseConfig$LicenseBean");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 由于构造函数是私有的，我们需要设置访问权限
        Constructor<?> constructor = null;
        try {
            constructor = aClass.getDeclaredConstructor(Integer.class,Long.class,Long.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        constructor.setAccessible(true); // 使私有构造函数可访问

        // 创建内部类的实例
        LicenseConfig.LicenseBean innerInstance = null;
        try {
            innerInstance = (LicenseConfig.LicenseBean) constructor.newInstance(999, 999L, 999L);

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return innerInstance;
    }
}
